/**
 * 包含多个直接更新state对象的方法的对象
 */
import {
  RECEIVE_ADDRESS,
  RECEIVE_SHOPTYPES,
  RECEIVE_SHOPS,
  RECEIVE_USER_INFO,
  RECEIVE_LOGOUT,
  RECEIVE_INFO,
  RECEIVE_FOODS,
  RECEIVE_RATINGS,
  SET_FOOD_INCREMENT,
  SET_FOOD_DECREMENT,
  RESET_SHOP_CART,
  GET_RATING,
  RECEIVE_SEARCH_SHOP
} from './mutation_type'
import Vue from 'vue'

export default {
  // 存储地址信息
  [RECEIVE_ADDRESS](state, {
    address
  }) {
    state.address = address
  },
  // 存储商品分类
  [RECEIVE_SHOPTYPES](state, {
    shopTypes
  }) {
    state.shopTypes = shopTypes
  },
  // 存储商品列表
  [RECEIVE_SHOPS](state, {
    shops
  }) {
    state.shops = shops
  },
  // 存储用户信息
  [RECEIVE_USER_INFO](state, {
    userInfo
  }) {
    state.userInfo = userInfo
  },
  // 登出
  [RECEIVE_LOGOUT](state) {
    state.userInfo = {}
  },
  // 存储商家信息
  [RECEIVE_INFO](state, {
    info
  }) {
    state.info = info
  },
  // 存储评论信息
  [RECEIVE_RATINGS](state, {
    ratings
  }) {
    state.ratings = ratings
  },
  // 存储商品信息
  [RECEIVE_FOODS](state, {
    foods
  }) {
    state.foods = foods
  },

  // 增加 food 数量
  [SET_FOOD_INCREMENT](state, {
    food
  }) {
    // 第一次增加
    if (!food.count) {
      Vue.set(food, "count", 1);
      state.cart.push(food);
    } else {
      // 因为food都是同一个对象，所以直接增加或减少就可以
      food.count++;
    }
  },
  // 减少 food 数量
  [SET_FOOD_DECREMENT](state, {
    food
  }) {
    // 如果当前值为0 则不能再进行自减操作
    if (food.count > 0) {
      // Vue.set(food, "count", food.count - 1);
      // 因为food都是同一个对象，所以直接增加或减少就可以
      food.count--;

      // 如何当前的count为0,那么就从购物车中删除那个食物
      // 利用数组的indexOf属性
      if (food.count === 0) {
        const index = (state.cart.indexOf(food));
        console.log(index);
        state.cart.splice(index, 1);
      }
    }
  },
  // 清空购物车
  [RESET_SHOP_CART](state){
    // 先把购物列表里面的food的count值置为0或者删除
    state.cart.forEach( item => item.count=0);

    console.log(state.cart);
    // 把购物车置空
    state.cart = [];
  },

  // 获取评论列表
  [GET_RATING](state, {ratings}){
    state.ratings = ratings;
  },

  // 更新 state中根据关键字查询的列表
  [RECEIVE_SEARCH_SHOP](state, {searchShop}){
    state.searchShop = searchShop
  }
}
